package Exchanger_15;
import java.util.concurrent.Exchanger;
public class 基础数据交换 {
    public static void main(String[] args) {
        final Exchanger<String> exchanger = new Exchanger<String>();
        final int THREAD_PAIRS = 5; // 5对交换线程

        // 创建线程对
        for (int i = 0; i < THREAD_PAIRS; i++) {
            final int pairId = i;

            // 线程A
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String dataA = "DataA-" + pairId;
                        System.out.println("线程A-" + pairId + " 准备交换: " + dataA);
                        Thread.sleep((long)(Math.random() * 500)); // 模拟处理时间

                        String received = exchanger.exchange(dataA);
                        System.out.println("线程A-" + pairId + " 收到: " + received);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "ThreadA-" + i).start();

            // 线程B
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String dataB = "DataB-" + pairId;
                        System.out.println("线程B-" + pairId + " 准备交换: " + dataB);
                        Thread.sleep((long)(Math.random() * 800)); // 模拟处理时间

                        String received = exchanger.exchange(dataB);
                        System.out.println("线程B-" + pairId + " 收到: " + received);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "ThreadB-" + i).start();
        }
    }
}